<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bamboowine.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="DFS&#x2F;DFS+记忆化搜索&#x2F;动态规划">
<meta property="og:type" content="article">
<meta property="og:title" content="目标和 (动态规划&#x2F;01背包)">
<meta property="og:url" content="https://bamboowine.gitee.io/2021/07/29/leetcode/%E7%9B%AE%E6%A0%87%E5%92%8C/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="DFS&#x2F;DFS+记忆化搜索&#x2F;动态规划">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729092459132.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729180317177.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729181540204.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729182814031.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729183756800.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729183935386.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729184212194.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729204311755.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729222317486.png">
<meta property="og:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729231820015.png">
<meta property="article:published_time" content="2021-07-29T07:04:28.000Z">
<meta property="article:modified_time" content="2021-07-29T15:28:12.669Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="leetcode周赛">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729092459132.png">

<link rel="canonical" href="https://bamboowine.gitee.io/2021/07/29/leetcode/%E7%9B%AE%E6%A0%87%E5%92%8C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>目标和 (动态规划/01背包) | Hexo</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      
      <!-- 修改title -->
      <h1 class="site-title"> BambooWine's Notes </h1>
      <p class="site-subtitle" style="opacity: 1; top: 0px;">努力吧, 朋友~</p>
      <!-- <h1 class="site-title">Hexo</h1> -->

      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bamboowine.gitee.io/2021/07/29/leetcode/%E7%9B%AE%E6%A0%87%E5%92%8C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Hexo">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          目标和 (动态规划/01背包)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-07-29 15:04:28 / 修改时间：23:28:12" itemprop="dateCreated datePublished" datetime="2021-07-29T15:04:28+08:00">2021-07-29</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>

          
            <div class="post-description">DFS/DFS+记忆化搜索/动态规划</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="494-目标和"><a href="#494-目标和" class="headerlink" title="494. 目标和"></a>494. 目标和</h1><h2 id="1-题目"><a href="#1-题目" class="headerlink" title="1. 题目"></a>1. 题目</h2><p><a href="https://leetcode-cn.com/problems/target-sum/" target="_blank" rel="noopener">题目链接</a></p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729092459132.png" alt="image-20210729092459132"></p>
<h2 id="2-题目分析"><a href="#2-题目分析" class="headerlink" title="2. 题目分析"></a>2. 题目分析</h2><p>先理一下题目逻辑；简言之就是 <code>nums</code> 数组<strong>每一个元素有正负两种</strong>状态，使其和为target，需要求得这样的组合数。</p>
<p>不难想到，<strong>target必须小于数组的所有元素之和</strong>，否则直接返回0即可</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        	...</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>后续的操作下面进行详细介绍：<strong>DFS</strong>、<strong>DFS+记忆化搜索</strong>、<strong>二维/一维dp</strong>、<strong>转化为01背包问题</strong>。</p>
<h2 id="3-DFS"><a href="#3-DFS" class="headerlink" title="3. DFS"></a>3. DFS</h2><h3 id="3-1-DFS"><a href="#3-1-DFS" class="headerlink" title="3.1 DFS"></a>3.1 DFS</h3><p><strong>每一个元素仅有两个状态，正和负</strong>。因此，所有的选取结果总共有<strong>2^n</strong>个。</p>
<p>在决策的时候，选取的过程类似一棵<strong>二叉树，左子树代表该元素为正，右子树代表该元素为负，而二叉树的深度代表当前元素所在的索引</strong>；以样例 <code>nums = [1,1,1,1], target = 2</code>进行说明，如图所示。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729180317177.png" alt="image-20210729180317177"></p>
<p>本图使用<strong>target - 元素所选正负值</strong>来表示的，所以呈现出一种“左孩子为减去元素，右孩子为加上元素值”的现象。</p>
<p>而我们的目标就是<strong>找所有的值为0的叶子节点的数目</strong>。</p>
<p>代码方面很简单，就是一个典型的<strong>前序遍历</strong>：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">return</span> helper(nums, target, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 前序遍历</span></span><br><span class="line"><span class="comment">    * @param nums: 原数组</span></span><br><span class="line"><span class="comment">    * @param target: 待合成的目标值</span></span><br><span class="line"><span class="comment">    * @param start: 元素所在索引/二叉树深度</span></span><br><span class="line"><span class="comment">    * @return int: 值为0的叶子节点的数目</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">helper</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target, <span class="keyword">int</span> start)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(start == nums.<span class="built_in">size</span>()) <span class="keyword">return</span> target == <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> left = helper(nums, target - nums[start], start + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">int</span> right = helper(nums, target + nums[start], start + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">return</span> left + right;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>分析代码复杂度，时间复杂度O(2^n)，不考虑递归工作栈的空间复杂度O(1)</p>
<p>本题的数据量，<code>nums</code> 数组的长度为 [0, 20]，数据量较小，所以可以预知暴力dfs是可以通过的。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729181540204.png" alt="image-20210729181540204"></p>
<h3 id="3-2-DFS-记忆化搜索"><a href="#3-2-DFS-记忆化搜索" class="headerlink" title="3.2 DFS + 记忆化搜索"></a>3.2 DFS + 记忆化搜索</h3><p>现在对上述代码进行优化。</p>
<p>在dfs遍历的过程中，会出现很多重复的节点。所谓<strong>重复的节点</strong>，是指<strong>二叉树同一深度中，值相等的节点</strong>，其需要由后续的元素进行合成，所以就出现了大量重复的计算。还是以上述样例进行说明，如图所示，同一颜色框中的子树是完全相同的，但是在dfs过程中还是做了重复的访问，这显然是没有必要的。</p>
<p>解决方法就是将访问过的节点用<strong>哈希表</strong>进行保存，<strong>包括其节点值、所在深度以及合成该节点值的方案数</strong>；在遍历的过程中，如果出现重复的节点，则直接返回。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729182814031.png" alt="image-20210729182814031"></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="built_in">unordered_map</span>&lt;<span class="built_in">string</span>, <span class="keyword">int</span>&gt; mp;</span><br><span class="line">        <span class="keyword">return</span> helper(nums, target, <span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 前序遍历</span></span><br><span class="line"><span class="comment">    * @param nums: 原数组</span></span><br><span class="line"><span class="comment">    * @param mp: 哈希表</span></span><br><span class="line"><span class="comment">    * @param target: 待合成的目标值</span></span><br><span class="line"><span class="comment">    * @param start: 元素所在索引/二叉树深度</span></span><br><span class="line"><span class="comment">    * @return int: 值为0的叶子节点的数目</span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">helper</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="built_in">unordered_map</span>&lt;<span class="built_in">string</span>, <span class="keyword">int</span>&gt;&amp; mp, <span class="keyword">int</span> target, <span class="keyword">int</span> start)</span></span>&#123;</span><br><span class="line">        <span class="built_in">string</span> key = to_string(target) + <span class="string">"_"</span> + to_string(start);</span><br><span class="line">        <span class="keyword">if</span>(mp.<span class="built_in">find</span>(key) != mp.<span class="built_in">end</span>()) <span class="keyword">return</span> mp[key];</span><br><span class="line">        <span class="keyword">if</span>(start == nums.<span class="built_in">size</span>())&#123;</span><br><span class="line">            mp[key] = target == <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">return</span> mp[key];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> left = helper(nums, mp, target - nums[start], start + <span class="number">1</span>);</span><br><span class="line">        <span class="keyword">int</span> right = helper(nums, mp, target + nums[start], start + <span class="number">1</span>);</span><br><span class="line">        mp[key] = left + right;</span><br><span class="line">        <span class="keyword">return</span> left + right;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不出意外，<strong>拿空间换时间</strong>。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729183756800.png" alt="image-20210729183756800"></p>
<p>本代码中，哈希表的 key = target + ‘_’ + start 来保证其<strong>唯一性</strong>，但是哈希表用string作为key的类型，并不是完美的解决方案，所以再下一节对key的定义进行修改，使用int类型来存储。</p>
<h3 id="3-3-修改哈希表key的定义"><a href="#3-3-修改哈希表key的定义" class="headerlink" title="3.3 修改哈希表key的定义"></a>3.3 修改哈希表key的定义</h3><p>上一节中 <code>string key = to_string(target) + &#39;_&#39; + to_string(start )</code>，同时观察本题的数据量：</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729183935386.png" alt="image-20210729183935386"></p>
<p>可以得出，在递归过程中 target ∈ [-2000, 2000]，start ∈ [0, 20]，为了包含target和start的信息，同时保证key的唯一性，可以对其进行如下定义：<code>int key = (target + 2001) * 20 + start</code> 对代码优化。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729184212194.png" alt="image-20210729184212194"></p>
<h2 id="4-动态规划"><a href="#4-动态规划" class="headerlink" title="4. 动态规划"></a>4. 动态规划</h2><p><strong>每一个元素仅有两个状态，正和负</strong>，排列组合使其和为target。</p>
<h3 id="4-1-二维dp"><a href="#4-1-二维dp" class="headerlink" title="4.1 二维dp"></a>4.1 二维dp</h3><h4 id="4-1-1-状态的定义"><a href="#4-1-1-状态的定义" class="headerlink" title="4.1.1 状态的定义"></a>4.1.1 状态的定义</h4><p>dp[ i ] [ j ]：用前 i 个元素合成结果 j 的方案数</p>
<p>i ∈ [0，n]</p>
<p>j ∈ [-sum，sum] ，其中sum代表数组所有元素的和</p>
<h4 id="4-1-2-状态转移方程"><a href="#4-1-2-状态转移方程" class="headerlink" title="4.1.2 状态转移方程"></a>4.1.2 状态转移方程</h4><p>考虑dp[ i ] [ j ]的推导：</p>
<ul>
<li>若当前元素<code>nums[i]</code> 为正，则<code>dp[i][j] = dp[i - 1][j - nums[i]]</code>，即前 <code>i - 1</code>个元素合成 <code>j - nums[i]</code>，再加上当前元素的正值，即可合成 j ；</li>
<li>若当前元素<code>nums[i]</code> 为负，则<code>dp[i][j] = dp[i - 1][j + nums[i]]</code>，即前 <code>i - 1</code>个元素合成 <code>j + nums[i]</code>，再加上当前元素的负值，即可合成 j ；</li>
</ul>
<p>综上所述：<strong><code>dp[i][j] = dp[i - 1][j - nums[i]] + dp[i - 1][j + nums[i]]</code></strong></p>
<h4 id="4-1-3-dp数组初始化"><a href="#4-1-3-dp数组初始化" class="headerlink" title="4.1.3 dp数组初始化"></a>4.1.3 dp数组初始化</h4><p>dp的递推需要对数组进行一定的初始化：</p>
<ul>
<li><p>首先dp数组全部元素可以设置为0</p>
</li>
<li><p>其次<code>dp[0][0] = 1</code>，含义是<strong>前0个元素合成0的方案数为1</strong></p>
<p><strong>初始化的原理：</strong></p>
<ul>
<li><p>首先数组的全部元素初始化为0是毋庸置疑的，符合逻辑</p>
</li>
<li><p>dp填表时，i 从1开始，所以<code>dp[0][j]</code>是需要初始化的；当 i = 1时，只能合成<code>nums[0]</code>和<code>-nums[0]</code>， 故只有<code>dp[1][nums[0]] = dp[1][-nums[0]] = 1</code>，该行的其余位置都是0（此处不要在意数组索引为负，只要按照状态定义理解，后续会介绍解决方案），再根据状态转移方程即可得到 <code>dp[0][0] = 1</code></p>
</li>
</ul>
</li>
</ul>
<h4 id="4-1-4-完整代码"><a href="#4-1-4-完整代码" class="headerlink" title="4.1.4 完整代码"></a>4.1.4 完整代码</h4><p>经过上述的分析，j的取值范围是[-sum，sum]，由于存在负值，所以 j 需要作一个sum的偏移量，使得其可映射到 [0, 2 * sum]，以至于可以在数组中正常使用。<strong>（上述分析不变，只需在dp的第二个索引加上偏移量sum）</strong></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="comment">// dp[i][j] 前i个数运算结果为j的表达式数目, j做一个sum的偏移，使其为正数</span></span><br><span class="line">        <span class="function"><span class="built_in">vector</span>&lt;<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&gt; <span class="title">dp</span><span class="params">(n + <span class="number">1</span>, <span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;(<span class="number">2</span> * sum + <span class="number">1</span>, <span class="number">0</span>))</span></span>;</span><br><span class="line">        dp[<span class="number">0</span>][sum] = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">            <span class="keyword">int</span> x = nums[i - <span class="number">1</span>];</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = -sum; j &lt;= sum; ++j)&#123;</span><br><span class="line">                <span class="keyword">if</span>(j - x + sum &gt;= <span class="number">0</span>)dp[i][j + sum] += dp[i - <span class="number">1</span>][j - x + sum];</span><br><span class="line">                <span class="keyword">if</span>(j + x + sum &lt;= <span class="number">2</span> * sum)dp[i][j + sum] += dp[i - <span class="number">1</span>][j + x + sum];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> dp[n][target + sum];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>上述代码时间复杂度O(n * sum)，空间复杂度O(n * sum)。</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729204311755.png" alt="image-20210729204311755"></p>
<h3 id="4-2-一维dp"><a href="#4-2-一维dp" class="headerlink" title="4.2 一维dp"></a>4.2 一维dp</h3><p>根据二维dp的代码可以看出，dp数组第 i 行的值仅仅依赖于第 i -1行的值，因此可以进行<strong>空间优化</strong>——只需要用滚动数组保存上一行的值即可。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        vector&lt;int&gt; dp(2 * sum + 1, 0), dp2(2 * sum + 1, 0);</span><br><span class="line">        dp[sum] = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i)&#123;</span><br><span class="line">            <span class="keyword">int</span> x = nums[i - <span class="number">1</span>];</span><br><span class="line">            <span class="built_in">memset</span>(dp2.data(), <span class="number">0</span>, dp2.<span class="built_in">size</span>() * <span class="keyword">sizeof</span>(<span class="keyword">int</span>));</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> j = -sum; j &lt;= sum; ++j)&#123;</span><br><span class="line">                <span class="keyword">if</span>(j - x + sum &gt;= <span class="number">0</span>)dp2[j + sum] += dp[j - x + sum];</span><br><span class="line">                <span class="keyword">if</span>(j + x + sum &lt;= <span class="number">2</span> * sum)dp2[j + sum] += dp[j + x + sum];</span><br><span class="line">            &#125;</span><br><span class="line">            dp = dp2;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> dp[target + sum];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>由于dp[j]取决于前后元素，所以需要用一个临时数组来完成空间优化</p>
<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729222317486.png" alt="image-20210729222317486"></p>
<h3 id="4-3-01背包问题"><a href="#4-3-01背包问题" class="headerlink" title="4.3 01背包问题"></a>4.3 01背包问题</h3><p>本题也可以用<strong>01背包问题</strong>的思维来解决。</p>
<ul>
<li>设最终的表达式中所有的正数之和为x，所有的负数之和为y(绝对值)，故 <code>x - y = target</code></li>
<li>而 <code>x + y = sum</code></li>
<li>可得<code>x = (target + sum) / 2</code></li>
</ul>
<p>所以本题就变化为：<strong>从<code>nums</code>数组中挑选若干个元素，使其和为<code>(target + sum) / 2</code></strong> 。</p>
<p>可以参考 <strong><a href="https://bamboowine.gitee.io/2021/07/28/leetcode/%E5%88%86%E5%89%B2%E7%AD%89%E5%92%8C%E5%AD%90%E9%9B%86%EF%BC%8801%E8%83%8C%E5%8C%85%EF%BC%89/">分割等和子集</a></strong>，这里给出一维dp的代码：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Solution</span> &#123;</span></span><br><span class="line"><span class="keyword">public</span>:</span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">findTargetSumWays</span><span class="params">(<span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt;&amp; nums, <span class="keyword">int</span> target)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">int</span> n = nums.<span class="built_in">size</span>();</span><br><span class="line">        <span class="keyword">int</span> sum = accumulate(nums.<span class="built_in">begin</span>(), nums.<span class="built_in">end</span>(), <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span>(target &gt; sum || (sum + target) % <span class="number">2</span>) <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">int</span> positive = (sum + target) / <span class="number">2</span>;</span><br><span class="line">        <span class="function"><span class="built_in">vector</span>&lt;<span class="keyword">int</span>&gt; <span class="title">dp</span><span class="params">(positive + <span class="number">1</span>, <span class="number">0</span>)</span></span>;</span><br><span class="line">        dp[<span class="number">0</span>] = <span class="number">1</span>;  <span class="comment">// 初始化</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> num : nums)&#123;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">int</span> x = positive; x &gt;= num; --x)&#123;</span><br><span class="line">                dp[x] += dp[x - num];</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> dp[positive];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/BambooWine/MyPhotos/raw/master/img/image-20210729231820015.png" alt="image-20210729231820015"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/leetcode%E5%91%A8%E8%B5%9B/" rel="tag"># leetcode周赛</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/07/28/leetcode/%E5%88%86%E5%89%B2%E7%AD%89%E5%92%8C%E5%AD%90%E9%9B%86%EF%BC%8801%E8%83%8C%E5%8C%85%EF%BC%89/" rel="prev" title="分割等和子集 (01背包)">
      <i class="fa fa-chevron-left"></i> 分割等和子集 (01背包)
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/07/30/leetcode/%E5%9B%9E%E6%96%87%E5%AD%90%E4%B8%B2/" rel="next" title="回文子串">
      回文子串 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#494-目标和"><span class="nav-number">1.</span> <span class="nav-text">494. 目标和</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-题目"><span class="nav-number">1.1.</span> <span class="nav-text">1. 题目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-题目分析"><span class="nav-number">1.2.</span> <span class="nav-text">2. 题目分析</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-DFS"><span class="nav-number">1.3.</span> <span class="nav-text">3. DFS</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-DFS"><span class="nav-number">1.3.1.</span> <span class="nav-text">3.1 DFS</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-DFS-记忆化搜索"><span class="nav-number">1.3.2.</span> <span class="nav-text">3.2 DFS + 记忆化搜索</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-修改哈希表key的定义"><span class="nav-number">1.3.3.</span> <span class="nav-text">3.3 修改哈希表key的定义</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-动态规划"><span class="nav-number">1.4.</span> <span class="nav-text">4. 动态规划</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1-二维dp"><span class="nav-number">1.4.1.</span> <span class="nav-text">4.1 二维dp</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-1-状态的定义"><span class="nav-number">1.4.1.1.</span> <span class="nav-text">4.1.1 状态的定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-2-状态转移方程"><span class="nav-number">1.4.1.2.</span> <span class="nav-text">4.1.2 状态转移方程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-3-dp数组初始化"><span class="nav-number">1.4.1.3.</span> <span class="nav-text">4.1.3 dp数组初始化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-4-完整代码"><span class="nav-number">1.4.1.4.</span> <span class="nav-text">4.1.4 完整代码</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-一维dp"><span class="nav-number">1.4.2.</span> <span class="nav-text">4.2 一维dp</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-01背包问题"><span class="nav-number">1.4.3.</span> <span class="nav-text">4.3 01背包问题</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt=" BambooWine "
      src="/images/avatar.jpg">

  <!-- 修改作者 -->
  <p class="site-author-name" itemprop="name"> BambooWine </p>
  <!-- <p class="site-author-name" itemprop="name">John Doe</p> -->

  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">21</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  
  <span class="author" itemprop="copyrightHolder">BambooWine</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
